/*
 * Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.supplier.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.BeanRet;
import com.pitop.core.entity.Page;
import com.pitop.core.entity.ProgressVO;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.SupplierException;
import com.pitop.core.tools.FileUtil;
import com.pitop.core.tools.StringTools;
import com.pitop.core.tools.excel.ExcelUtils;
import com.pitop.material.dao.MaterialDAO;
import com.pitop.material.entity.Material;
import com.pitop.payment.entity.PaymentTerm;
import com.pitop.payment.service.PaymentTermSV;
import com.pitop.supplier.VO.SupplierExcel;
import com.pitop.supplier.dao.SupplierDAO;
import com.pitop.supplier.entity.Supplier;
import com.pitop.supplier.entity.SupplierState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("supplierSV")
@Slf4j
public class SupplierSVImpl extends BaseSVImpl<Supplier, Long> implements SupplierSV {

    @Autowired
    private SupplierDAO supplierDAO;

    @Autowired
    private MaterialDAO materialDAO;

    @Autowired
    private SupplierCategorySVImpl supplierCategorySV;

    @Autowired
    private PaymentTermSV paymentTermSV;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return supplierDAO;
    }

    /**
     * 保存account对象
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    public void save(Supplier entity) throws BaseException {
        entity.setCode(String.valueOf(uidGenerator.getUID()));
        entity.setState(SupplierState.Enable.name());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        super.save(entity);
    }

    /**
     * 加载一个对象Supplier
     *
     * @param id * @param code 编码
     * @return Supplier
     */
    @Override
    public Supplier load(Long id, String code) {
        if (id == null && code == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return supplierDAO.load(param);
    }

    /**
     * 加载一个对象Supplier 通过id
     *
     * @param id
     * @return Supplier
     */
    @Override
    public Supplier loadById(Long id) {
        if (id == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return supplierDAO.loadById(id);
    }

    /**
     * 加载一个对象Supplier 通过code
     *
     * @param code 编码
     * @return Supplier
     */
    @Override
    public Supplier loadSuppAndMaterial(String code) {
        if (code == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> params = new HashedMap();
        params.put("suppierCode", code);
        List<Material> materials = materialDAO.listBySuppierCode(code);
        Supplier supplier = supplierDAO.loadByCode(code);
        if (supplier != null) {
            supplier.setMaterials(materials);
        }
        return supplier;
    }

    /**
     * 加载一个对象Supplier 通过code
     *
     * @param code 编码
     * @return Supplier
     */
    @Override
    public Supplier loadByCode(String code) {
        if (code == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> params = new HashedMap();
        params.put("suppierCode", code);
        Supplier supplier = supplierDAO.loadByCode(code);

        return supplier;
    }

    /**
     * 加载一个对象Supplier 通过email
     *
     * @param email 邮箱
     * @return Supplier
     */
    @Override
    public Supplier loadByEmail(String email) {
        if (email == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> params = new HashedMap();
        params.put("email", email);
        return supplierDAO.load(params);
    }

    /**
     * 加载一个对象Supplier 通过mobile
     *
     * @param mobile 移动电话
     * @return Supplier
     */
    @Override
    public Supplier loadByMobile(String mobile) {
        if (mobile == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> params = new HashedMap();
        params.put("mobile", mobile);
        return supplierDAO.load(params);
    }

    /**
     * 加载一个对象Supplier 通过name
     *
     * @param name 供应商名称
     * @return Supplier
     */
    @Override
    public Supplier loadByName(String name) {
        if (name == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> params = new HashedMap();
        params.put("name", name);
        return supplierDAO.load(params);
    }


    /**
     * 根据主键id,oldStates 共同更新 Supplier 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(Long id, SupplierState newState, SupplierState... oldStates) {
        if (id == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        supplierDAO.updateStateById(id, new Date(), newState.name(), states);
    }

    /**
     * 根据主键code,oldStates 共同更新 Supplier 的状态到newState状态
     *
     * @param code      编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateByCode(String code, SupplierState newState, SupplierState... oldStates) {
        if (code == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        supplierDAO.updateStateByCode(code, new Date(), newState.name(), states);
    }

    /**
     * 根据主键id 更新 Supplier 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
    public void updateById(Long id, SupplierState state) {
        if (id == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        supplierDAO.updateById(id, state.name(), new Date());
    }

    /**
     * 根据主键code 更新 Supplier 的状态到另一个状态
     *
     * @param code  编码
     * @param state 状态
     */
    @Override
    public void updateByCode(String code, SupplierState state) {
        if (code == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        supplierDAO.updateByCode(code, state.name(), new Date());
    }


    /**
     * 删除对象Supplier
     *
     * @param id * @param code 编码
     * @return Supplier
     */
    @Override
    public void delete(Long id, String code) {
        if (id == null && code == null) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        supplierDAO.delete(param);
    }


    /**
     * 查询Supplier分页
     *
     * @param supplier 对象
     * @param offset   查询开始行
     * @param limit    查询行数
     * @return List<Supplier>
     */
    @Override
    public List<Supplier> list(Supplier supplier, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map;
        if (supplier != null) {
            map = JSON.parseObject(JSON.toJSONString(supplier, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return supplierDAO.list(map, new RowBounds(offset, limit));
    }

    /**
     * 查询Supplier
     *
     * @param materialCode 编码
     * @return List<Supplier>
     */
    @Override
    public List<Supplier> loadListByMaterialCode(String materialCode) {
        if (StringTools.isEmpty(materialCode)) {
            throw new SupplierException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return supplierDAO.loadListByMaterialCode(materialCode);
    }

    @Override
    public int count(Supplier supplier) {
        Map<String, Object> map;
        if (supplier != null) {
            map = JSON.parseObject(JSON.toJSONString(supplier, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return supplierDAO.count(map);
    }

    /**
     * 查询Supplier分页
     *
     * @param id     * @param code  编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Supplier>
     */
    @Override
    public List<Supplier> list(Long id, String code, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return supplierDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(Long id, String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return supplierDAO.count(param);
    }

    /**
     * * 上传Excel文件，批量导入代理商
     * 1.生成供应商类型sql,保存着supplier.txt文件中
     * 2.把供应商类型插入到数据库中，插入过程去重
     * 3.生成支付方式类型sql,保存到supplier.txt文件中
     * 4.把支付方式插入到数据库中，插入过程去重
     * 5.生成供应商sql,同时根据供应类型，支付方式找到对应的供应商类型编码和支付方式编码
     * 6.把供应插入到数据库中，插入过程去重，并统计失败数据，成功数据保存到supplier.txt文件中
     *
     * @param limitFileInputStream 导入文件
     * @param originalFilename     文件名
     * @return BeanRet
     */
    @Override
    public BeanRet importSupplier(InputStream limitFileInputStream, String originalFilename) {
        //读取excel文件
        List<SupplierExcel> supplierExcels = ExcelUtils.readExcel(limitFileInputStream, originalFilename, SupplierExcel.class);
        int rightNum = 0;   //成功导入数量
        int errorNum = 0;   //失败数量
        ProgressVO progressVO = new ProgressVO(supplierExcels.size(), errorNum);
        PaymentTerm paymentTerm;
        StringBuffer paymentSql = new StringBuffer();
        StringBuffer paymentSqlFlag;

        //生成支付方式sql
        for (SupplierExcel supplierExcel : supplierExcels) {
            //生成支付方式sql保存到文件中
            paymentTerm = paymentTermSV.loadByPayment(supplierExcel.getPaymentTerm());
            if (paymentTerm == null) {
                paymentSqlFlag = new StringBuffer();
                paymentSqlFlag.append("INSERT INTO payment_term(code, payment) VALUES(");
                paymentSqlFlag.append(uidGenerator.getUID()).append(",").append("'" + supplierExcel.getPaymentTerm() + "'").append(");").append("\r\n");
                paymentSql.append(paymentSqlFlag);
                paymentSqlFlag = null;
            }
        }
        //生成供应商类型sql
        //生成供应商sql
        Supplier supplier;
        StringBuffer supplierSql = new StringBuffer();
        StringBuffer supplierSqlFlag;
        for (SupplierExcel supplierExcel : supplierExcels) {
            //生成支付方式sql保存到文件中
            supplier = this.loadByName(supplierExcel.getName());
            if (supplier == null) {
                supplierSqlFlag = new StringBuffer();
                supplierSqlFlag.append("INSERT INTO supplier(code, name,englishName,contacts,payment_term,credit_rating,website,address,english_address,email,mobile,state) VALUES(");
                supplierSqlFlag.append("'" + uidGenerator.getUID()).append("','");
                supplierSqlFlag.append(supplierExcel.getName()).append("','");
                supplierSqlFlag.append(supplierExcel.getEnglishName()).append("','");
                supplierSqlFlag.append(supplierExcel.getContacts()).append("','");
                supplierSqlFlag.append(supplierExcel.getPaymentTerm()).append("','");
                supplierSqlFlag.append(5).append("','");
                supplierSqlFlag.append(supplierExcel.getWebsite()).append("','");
                supplierSqlFlag.append(supplierExcel.getAddress()).append("','");
                supplierSqlFlag.append(supplierExcel.getEnglishAddress()).append("','");
                supplierSqlFlag.append(supplierExcel.getEmail()).append("','");
                supplierSqlFlag.append(supplierExcel.getMobile()).append("','");
                supplierSqlFlag.append(SupplierState.Enable.name()).append("'");
                supplierSqlFlag.append(");").append("\r\n");
                supplierSql.append(supplierSqlFlag);
                supplierSqlFlag = null;
            }
        }
        try {
            File file = FileUtil.creatFile("C:\\supplier", "sql");
            FileOutputStream fos = new FileOutputStream(file);
            byte[] paymentSqlByte = paymentSql.toString().getBytes();
            fos.write(paymentSqlByte);
            byte[] supplierSqlByte = supplierSql.toString().getBytes();
            fos.write(supplierSqlByte);
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
